#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "network.h"
#include "common.h"
#include "online_list.h"

int connect_to_server() {
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd < 0) {
        perror("socket 创建失败");
        return -1;
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);

    if (connect(socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr))) {
        perror("连接服务器失败");
        close(socket_fd);
        return -1;
    }

    return socket_fd;
}

void* recv_thread_func(void* arg) {
    struct thread_args* args = (struct thread_args*)arg;
    int socket_fd = args->socket_fd;
    int* is_running = args->is_running;
    struct online_user** online_list = args->online_list;

    char buf[1024];
    int ret;

    while (*is_running) {
        memset(buf, 0, sizeof(buf));
        ret = recv(socket_fd, buf, sizeof(buf) - 1, 0);

        if (ret > 0) {
            buf[ret] = '\0';

            if (strncmp(buf, "LOGIN_SUCCESS:", 14) == 0) {
                char username[30] = {0};
                char account[ACCOUNT_LENGTH + 1] = {0};
                if (sscanf(buf + 14, "%29[^:]:%10s", username, account) == 2) {
                    printf("\n=== 登录成功! ===\n");
                    printf("用户名: %s\n", username);
                    printf("账号: %s\n", account);
                    printf("================\n");
                }
                printf("> ");
                fflush(stdout);
            } 
            else if (strncmp(buf, "ONLINE:", 7) == 0) {
                char* token = strtok(buf + 7, ":");
                free_online_users(*online_list);
                *online_list = NULL;

                while (token != NULL) {
                    char account[ACCOUNT_LENGTH + 1] = {0};
                    char username[30] = {0};

                    if (sscanf(token, "%10[^,],%29[^\n]", account, username) == 2) {
                        add_online_user(online_list, account, username);
                    }

                    token = strtok(NULL, ":");
                }

                print_online_users(*online_list);
            } 
            else if (strncmp(buf, "PRIVATE:", 8) == 0) {
                char sender[ACCOUNT_LENGTH + 1] = {0};
                char message[256] = {0};

                if (sscanf(buf + 8, "%10[^:]:%255[^\n]", sender, message) == 2) {
                    printf("\n[私聊] 来自 %s: %s\n", sender, message);
                    printf("> ");
                    fflush(stdout);
                }
            } 
            else {
                printf("\n%s\n", buf);
                printf("> ");
                fflush(stdout);
            }
        } 
        else if (ret == 0) {
            printf("\n服务器已断开连接\n");
            *is_running = 0;
            break;
        } 
        else {
            perror("recv error");
            *is_running = 0;
            break;
        }
    }

    free(arg);
    return NULL;
}

void write_message(int socket_fd, struct online_user* online_list) {
    printf("\n开始聊天 (输入命令: /list 查看在线用户, /to <账号> <消息> 私聊, /exit 退出)\n");
    printf("> ");
    fflush(stdout);

    while (1) {
        char input[256] = {0};
        if (fgets(input, sizeof(input), stdin) == NULL) {
            continue;
        }

        input[strcspn(input, "\n")] = 0;

        if (strcmp(input, "/exit") == 0) {
            break;
        } 
        else if (strcmp(input, "/list") == 0) {
            send(socket_fd, "LIST", 4, 0);
            printf("> ");
            fflush(stdout);
        } 
        else if (strncmp(input, "/to ", 4) == 0) {
            char recipient[ACCOUNT_LENGTH + 1] = {0};
            char message[256] = {0};

            if (sscanf(input + 4, "%10s %255[^\n]", recipient, message) == 2) {
                char formatted_msg[300];
                snprintf(formatted_msg, sizeof(formatted_msg), "PRIVATE:%s:%s", recipient, message);
                send(socket_fd, formatted_msg, strlen(formatted_msg), 0);
            } 
            else {
                printf("格式错误! 使用: /to <账号> <消息>\n");
                printf("> ");
                fflush(stdout);
            }
        } 
        else {
            send(socket_fd, input, strlen(input), 0);
            printf("> ");
            fflush(stdout);
        }
    }
}